<template>
  <div class="product">
    <div v-if="!isAddShow" class="product_list">
      <!--头部功能 搜索 新增 导出  导入 -->
      <div class="filter-container">
        <el-input v-model="listQuery.title"
                  placeholder="商品标题" style="width: 100px;"
                  class="filter-item"
                  @keyup.enter.native="handleFilter"/>
        <el-select v-model="listQuery.importance"
                   placeholder="商品类型"
                   clearable style="width: 120px"
                   class="filter-item">
          <el-option v-for="item in importanceOptions"
                     :key="item"
                     :label="item"
                     :value="item"/>
        </el-select>
        <el-select v-model="listQuery.type"
                   placeholder="洗护类型"
                   clearable class="filter-item"
                   style="width: 130px">
          <el-option v-for="item in calendarTypeOptions"
                     :key="item.key"
                     :label="item.display_name+'('+item.key+')'"
                     :value="item.key"/>
        </el-select>
        <el-select v-model="listQuery.sort"
                   style="width: 140px"
                   class="filter-item"
                   @change="handleFilter">
          <el-option v-for="item in sortOptions"
                     :key="item.key"
                     :label="item.label"
                     :value="item.key"/>
        </el-select>
        <el-button v-waves
                   class="filter-item"
                   type="primary"
                   icon="el-icon-search"
                   @click="handleFilter"
        >
          搜索
        </el-button>
        <el-button class="filter-item"
                   style="margin-left: 10px;"
                   type="primary"
                   icon="el-icon-edit"
                   @click="handleCreate">
          新增商品
        </el-button>
        <el-button v-waves
                   :loading="downloadLoading"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-download"
                   @click="handleDownload">
          导出
        </el-button>

        <el-button v-waves
                   :loading="downloadLoading"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-upload2"
                   @click="handleDownload">
          导入
        </el-button>
      </div>
      <!--商品管理列表+操作按钮-->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                         :class-name="getSortClass('id')">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品标题"
                         prop="title"
                         sortable="custom"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品图片"
                         prop="pic"
                         sortable="custom"
                         align="center"
                         width="120">
          <template slot-scope="scope">
            <img width="80" :src="scope.row.pic">
          </template>
        </el-table-column>

        <el-table-column label="商品价格"
                         prop="price"
                         sortable="custom"
                         align="center"
                         width="150">
          <template slot-scope="scope">
            <span>￥{{ scope.row.price.toFixed(2)}}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品库存"
                         prop="stock"
                         sortable="custom"
                         align="center"
                         width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.stock}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Status" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button v-if="row.status!='published'" size="mini" type="success"
                       @click="handleModifyStatus(row,'published')">
              发布
            </el-button>
            <el-button v-if="row.status!='draft'"
                       size="mini"
                       @click="handleModifyStatus(row,'draft')">
              下架
            </el-button>
            <el-button
              v-if="row.status!='deleted'"
              size="mini" type="danger"
              @click="handleDel(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.page"
                  :limit.sync="listQuery.limit"
                  @pagination="getList"/>
    </div>
    <!--新增商品跳转页面 merchant-->
    <div v-else class="add_product">
      <!--form表单-->
      <el-form ref="form" :model="form" style="margin: 10px auto" label-width="80px">
        <el-form-item label="商品封面">
          <el-upload multiple
                     :limit="1"
                     :action="'http://localhost:8080/upload'"
                     list-type="picture-card"
                     :on-preview="handlePictureCardPreview"
                     :on-success="handleUploadSuccess"
                     :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品原价">
          ￥
          <el-input-number v-model="form.oldprice"
                           :precision="2"
                           :step="0.1"
                           :min="0">
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品现价">
          ￥
          <el-input-number v-model="form.price"
                           :precision="2"
                           :step="0.1"
                           :min="0">
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品库存">
          <el-input-number v-model="form.stock"
                           :precision="0"
                           :step="1"
                           :min="0">
          </el-input-number>
          单位
        </el-form-item>
        <el-form-item label="商品标题">
          <el-input
            style="width: 50%"
            placeholder="请输入商品标题"
            v-model="form.title"
            clearable>
          </el-input>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-autocomplete
            readonly
            popper-class="my-autocomplete"
            v-model="form.classificationName"
            :fetch-suggestions="querySearch1"
            placeholder="请输入分类名"
            @select="handleSelect1">
            <i
              class="el-icon-edit el-input__icon"
              slot="suffix"
              @click="handleIconClick">
            </i>
            <template slot-scope="{ item }">
              <!--<div class="name">{{ item.value }}</div>-->
              <span class="addr">{{ item.classificationName }}</span>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="商家名称">
          <el-autocomplete
            readonly
            style="width: 300px;"
            popper-class="my-autocomplete"
            v-model="form.merchantName"
            :fetch-suggestions="querySearch"
            placeholder="请输入商家名称"
            @select="handleSelect">
            <i
              class="el-icon-edit el-input__icon"
              slot="suffix"
              @click="handleIconClick">
            </i>
            <template slot-scope="{ item }">
              <!--<div class="name">{{ item.id }}</div>-->
              <span class="addr">{{ item.name }}</span>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="商品详情">
          <vue-ueditor-wrap
            v-model="form.detail"
            :config="myConfig"></vue-ueditor-wrap>
        </el-form-item>
        <hr/>
        <el-form-item>
          <el-button :loading="saving"
                     type="primary"
                     @click="onSubmit">
            立即创建
          </el-button>

          <el-button @click="getOut">
            取消
          </el-button>
        </el-form-item>
      </el-form>
      <!--文件缩列图组件-->
    </div>

  </div>
</template>

<script>
  import waves from '@/directive/waves'
  import ajax from '@/utils/baseurl'
  import Pagination from '@/components/Pagination'
  import VueUeditorWrap from 'vue-ueditor-wrap'
  import $ from 'jquery'

  var p;
  var token = localStorage.currentUser
    ?JSON.parse(localStorage.currentUser).token:"";
  export default {
    name: 'commodityManagement',
    directives: { waves },
    components: { Pagination, VueUeditorWrap },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        saving:false,
        token:token,
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 180,
          // 初始容量宽度
          initialFrameWidth: '50%',
          // 上传文件接口（这个地址我为了方便各位体验文件上传）
         serverUrl: 'http://47.98.223.132:8080/find_upload_config',
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
         // serverUrl: 'http://39.96.94.201:8090/find_upload_config',
          UEDITOR_HOME_URL: '/UEditor/'
        },
        isAddShow: false,
        temp: {
          id: '',
          title: '',
          pic: '',
          price: '',
          stock: '',
          buyCount: '',
          createDate: '',
          detail: '',
          oldPrice: '',
          type1: '',
          type2: '',
          count: ''
        },
        total: 0,
        tableKey: 0,
        list: null,
        statusOptions: ['published', 'draft', 'deleted'],
        listLoading: false,
        downloadLoading: false,
        dialogFormVisible: false,
        dialogStatus: '',
        rules: {},
        pvData: [],
        textMap: {
          update: '修改',
          create: '新增'
        },
        dialogPvVisible: false,
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: ['特价', '售罄', '正常'],
        calendarTypeOptions: [
          { key: '快速洗', display_name: '快速洗' },
          { key: '按打包价洗护', display_name: '按打包价洗护' },
          { key: '热门推荐', display_name: '热门推荐' },
          { key: '精品推荐', display_name: '精品推荐' },
          { key: '按件洗', display_name: '按件洗' },
          { key: '奢护洗', display_name: '奢护洗' },
          { key: '鞋类洗', display_name: '鞋类洗' },
          { key: '家纺洗', display_name: '家纺洗' }
        ],
        sortOptions: [{ label: 'ID升序', key: '+id' }, { label: 'ID降序', key: '-id' }],
        form: {
          pic:this.dialogImageUrl,
          oldprice: 100.0,
          price: 100.00,
          stock: 100,
          title: '',
          merchantName: '',
          classificationName:'',
          classificationId:0,
          merchantId:0,
          detail:''
        },
        classifications:[],
        merchants: [],
        dialogImageUrl: '',
        dialogVisible: false

      }
    },
    created() {
      p = this
      p.getList()
      p.getMerchantList()
      p.getclassificationList()
    },
    mounted() {
      this.merchants = this.getMerchantList();
      this.classifications=this.getclassificationList();
    },
    methods: {
      getOut(){
        p.isAddShow=false;
      },
      handleUploadSuccess(response,file,fileList){
        for(var i=0;i<fileList.length;i++){
          this.form.pic = fileList[i].response.url;
        }
        console.log(this.form.pic);
        console.log(fileList);
      },
      getclassificationList(){
        var p=this;
        ajax("classification/getAllClassification",{},function(res) {
          console.log(res)
          res=JSON.parse(res)
          p.classifications=res.list;

        })
      },
      getMerchantList(){
        var p=this;
        ajax("merchant/getAllMerchant",{},function(res) {
          console.log(res)
          res=JSON.parse(res)
          p.merchants=res.list;

        })
      },
      querySearch(queryString, cb) {
        var merchants = this.merchants;
        var results =
          queryString
            ? merchants.filter(this.createFilter(queryString)) : merchants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      querySearch1(queryString, cb) {
        var classifications = this.classifications;
        var results =
          queryString
            ? classifications.filter(this.createFilter1(queryString)) : classifications;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      createFilter1(queryString) {
        return (restaurant) => {
          return (restaurant.classificationName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      loadAll() {
        return [
          { "value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
          { "value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号" },
          { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
          { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
          { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
          { "value": "贡茶", "address": "上海市长宁区金钟路633号" },
          { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
          { "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },
          { "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },
          { "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },
          { "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },
          { "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },
          { "value": "Monica摩托主题咖啡店", "address": "嘉定区江桥镇曹安公路2409号1F，2383弄62号1F" },
          { "value": "浮生若茶（凌空soho店）", "address": "上海长宁区金钟路968号9号楼地下一层" },
          { "value": "NONO JUICE  鲜榨果汁", "address": "上海市长宁区天山西路119号" },
          { "value": "CoCo都可(北新泾店）", "address": "上海市长宁区仙霞西路" },
          { "value": "快乐柠檬（神州智慧店）", "address": "上海市长宁区天山西路567号1层R117号店铺" },
          { "value": "Merci Paul cafe", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },
          { "value": "猫山王（西郊百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },
          { "value": "枪会山", "address": "上海市普陀区棕榈路" },
          { "value": "纵食", "address": "元丰天山花园(东门) 双流路267号" },
          { "value": "钱记", "address": "上海市长宁区天山西路" },
          { "value": "壹杯加", "address": "上海市长宁区通协路" },
          { "value": "唦哇嘀咖", "address": "上海市长宁区新泾镇金钟路999号2幢（B幢）第01层第1-02A单元" },
          { "value": "爱茜茜里(西郊百联)", "address": "长宁区仙霞西路88号1305室" },
          { "value": "爱茜茜里(近铁广场)", "address": "上海市普陀区真北路818号近铁城市广场北区地下二楼N-B2-O2-C商铺" },
          { "value": "鲜果榨汁（金沙江路和美广店）", "address": "普陀区金沙江路2239号金沙和美广场B1-10-6" },
          { "value": "开心丽果（缤谷店）", "address": "上海市长宁区威宁路天山路341号" },
          { "value": "超级鸡车（丰庄路店）", "address": "上海市嘉定区丰庄路240号" },
          { "value": "妙生活果园（北新泾店）", "address": "长宁区新渔路144号" },
          { "value": "香宜度麻辣香锅", "address": "长宁区淞虹路148号" },
          { "value": "凡仔汉堡（老真北路店）", "address": "上海市普陀区老真北路160号" },
          { "value": "港式小铺", "address": "上海市长宁区金钟路968号15楼15-105室" },
          { "value": "蜀香源麻辣香锅（剑河路店）", "address": "剑河路443-1" },
          { "value": "北京饺子馆", "address": "长宁区北新泾街道天山西路490-1号" },
          { "value": "饭典*新简餐（凌空SOHO店）", "address": "上海市长宁区金钟路968号9号楼地下一层9-83室" },
          { "value": "焦耳·川式快餐（金钟路店）", "address": "上海市金钟路633号地下一层甲部" },
          { "value": "动力鸡车", "address": "长宁区仙霞西路299弄3号101B" },
          { "value": "浏阳蒸菜", "address": "天山西路430号" },
          { "value": "四海游龙（天山西路店）", "address": "上海市长宁区天山西路" },
          { "value": "樱花食堂（凌空店）", "address": "上海市长宁区金钟路968号15楼15-105室" },
          { "value": "壹分米客家传统调制米粉(天山店)", "address": "天山西路428号" },
          { "value": "福荣祥烧腊（平溪路店）", "address": "上海市长宁区协和路福泉路255弄57-73号" },
          { "value": "速记黄焖鸡米饭", "address": "上海市长宁区北新泾街道金钟路180号1层01号摊位" },
          { "value": "红辣椒麻辣烫", "address": "上海市长宁区天山西路492号" },
          { "value": "(小杨生煎)西郊百联餐厅", "address": "长宁区仙霞西路88号百联2楼" },
          { "value": "阳阳麻辣烫", "address": "天山西路389号" },
          { "value": "南拳妈妈龙虾盖浇饭", "address": "普陀区金沙江路1699号鑫乐惠美食广场A13" }
        ];
      },
      handleSelect(item) {
        this.form.merchantName=item.name;
        this.form.merchantId=item.id;
        console.log(item);
      },
      handleSelect1(item) {
        this.form.classificationName=item.classificationName;
        this.form.classificationId=item.id;
        console.log(item);
      },
      handleIconClick(ev) {
        console.log(ev);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      updateData() {
        p.createData()
      },
      resetTemp() {
        p.temp = {
          id: 0,
          title: '',
          pic: '',
          price: 100.00,
          stock: 0
        }
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
              ajax('product/updateProduct', p.temp, function(data) {
                console.log(data)
                if (data) {
                  p.dialogFormVisible = false
                  p.getList()
                  p.$notify({
                    title: '搞定',
                    message: '修改成功！',
                    type: 'success',
                    duration: 2000
                  })
                }
              })

          }
        })
      },
      onSubmit() {
        this.saving=true;
        console.log(p.form.pic)
        ajax('product/addProduct', p.form, function(data) {
          console.log(data)
          if (data) {
            p.dialogFormVisible = false
            p.getList()
            p.$notify({
              title: '搞定',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
          }
        })
        p.isAddShow=false;
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      getList() {
        this.listLoading = true
        ajax('product/getPage', this.listQuery, function(res) {
          console.log(res)
          res = JSON.parse(res)
          p.list = res.page.list
          //page limit赋值
          p.total = parseInt(res.page.totalCount)
          p.listLoading = false
        })
      },
      sortChange(data) {

      },
      handleFilter() {
        p.listQuery.page = 1
        p.getList()
      },
      handleCreate() {
        p.dialogStatus = 'create'
        p.dialogFormVisible = true
        this.isAddShow = true
      },
      handleUpdate(row) {
        p.temp = Object.assign({}, row)
        p.dialogStatus = 'update'
        p.dialogFormVisible = true
        p.$nextTick(() => {
          p.$refs['dataForm'].clearValidate()
        })
      },
      handleDownload() {

      },
      getSortClass: function(key) {

      },
      handleModifyStatus() {
        p.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      handleDel(row) {
        var p = this
        this.$confirm('此操作将永久删除该商品，时候继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax('product/deleteProduct', { 'id': row.id }, function(data) {
            if (data) {
              p.getList()
              p.$message({
                type: 'success',
                message: '删除成功！'
              })
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }

    }
  }
</script>
<style>
  .my-autocomplete {

    li {
      line-height: normal;
      padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }

  }
}
</style>
